<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 && commissionType == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :is-emit="false"
            :editModel="editModel == 0 ? '' : ''"
            @selectOrg="selectOrg"
            @getProjectInfo="getProjectInfo"
          >
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table
                  businessCode="BM27"
                  :uploadArrys.sync="form.fileInfoList"
                ></l-table>
                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
              </template>
              <file-link
                v-else
                :fileList="form.fileInfoList"
                style="margin-top: -3px"
              ></file-link>
            </template>
          </custom-form>
        </a-card>
        <a-card
          v-if="form.pmPaymentAmount || form.pmPaymentAmount == 0"
          :bordered="false"
        >
          <title-name title="项目经理意见"></title-name>
          <custom-form
            :formList="auditSWJL"
            :form="form"
            :editModel="editModel == 0 ? '' : ''"
          >
            <template #PDLXMJL>
              <a-form-model-item
                label=""
                class="item"
              >
                同意该同志在该项目补缴风险金
                <a-form-model-item
                  :colon="false"
                  label=" "
                  prop="pmPaymentAmount"
                  :style="{ display: 'inline-block' }"
                >
                  <a-input-number
                    :min="0"
                    style="width: 350px; margin-top: -34px"
                    placeholder="请输入"
                    disabled
                    v-model="form.pmPaymentAmount"
                  />
                </a-form-model-item>
                元
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
        <a-card
          v-if="form.cldPaymentAmount || form.cldPaymentAmount == 0"
          :bordered="false"
        >
          <title-name title="分公司商务法务部经理意见"></title-name>
          <custom-form
            :formList="auditBCSWFWBJL"
            :form="form"
            :editModel="editModel == 0 ? '' : ''"
          >
            <template #BCSWFWBJL>
              <a-form-model-item
                label=""
                class="item"
              >
                同意该同志在该项目补缴风险金
                <a-form-model-item
                  :colon="false"
                  label=" "
                  prop="cldPaymentAmount"
                  :style="{ display: 'inline-block' }"
                >
                  <a-input-number
                    :min="0"
                    style="width: 350px; margin-top: -34px"
                    placeholder="请输入"
                    disabled
                    v-model="form.cldPaymentAmount"
                  />
                </a-form-model-item>
                元
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
        <a-card
          v-if="form.economicsPaymentAmount || form.economicsPaymentAmount == 0"
          :bordered="false"
        >
          <title-name title="分公司总经济师意见"></title-name>
          <custom-form
            :formList="auditBCLZJJS"
            :form="form"
            :editModel="editModel == 0 ? '' : ''"
          >
            <template #BCLZJJS>
              <a-form-model-item
                label=""
                class="item"
              >
                同意该同志在该项目补缴风险金
                <a-form-model-item
                  :colon="false"
                  label=" "
                  prop="economicsPaymentAmount"
                  :style="{ display: 'inline-block' }"
                >
                  <a-input-number
                    :min="0"
                    style="width: 350px; margin-top: -34px"
                    placeholder="请输入"
                    disabled
                    v-model="form.economicsPaymentAmount"
                  />
                </a-form-model-item>
                元
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
        <a-card v-if="commissionType == 1 || form.commissionFileInfoList.length > 0">
          <title-name title="收据上传"></title-name>
          <custom-form
            :formList="formUpload"
            :form="form"
            :editModel="editModel == 0 ? '' : ''"
          >
            <!-- 附件上传 -->
            <template #commissionFileInfoList>
              <template v-if="commissionType == 1">
                <l-table
                  :disabled="resolveInfo"
                  businessCode="BM27"
                  :uploadArrys.sync="form.commissionFileInfoList"
                ></l-table>
                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
              </template>
              <file-link
                v-else
                :fileList="form.commissionFileInfoList"
                style="margin-top: -3px"
              ></file-link>
            </template>
          </custom-form>
        </a-card>

        <!-- 页脚操作栏 -->
        <div
          class="btn_box page-btn-right-top"
          v-if="editModel != 0"
        >
          <!-- <a-button class="button_right" v-if="id != '' && form.auditStatus == 'DRAFT'" type="danger" @click="handleRemove()"
                    >删除草稿</a-button
                > -->
          <a-button
            v-if="resolveInfo"
            @click="handleActiveClose"
          >关闭</a-button>
          <template v-else>
            <a-button
              class="button_right"
              v-if="form.status == 'REJECTED'"
              type="primary"
              :loading="loadingBtn.REJECTED"
              @click="handleSubmit('REJECTED')"
            >保存</a-button>
            <a-button
              v-else
              class="button_right"
              type="primary"
              :loading="loadingBtn.DRAFT"
              @click="handleSubmit('DRAFT')"
            >保存草稿</a-button>
            <a-button
              class="button_right"
              type="primary"
              :loading="loadingBtn.SUBMITTED"
              @click="handleSubmit('SUBMITTED')"
            >提交</a-button>
            <a-button @click="handleActiveClose">关闭</a-button>
          </template>
        </div>
        <div
          class="btn_box page-btn-right-top"
          v-else
        >
          <BasePrintButton
            class="button_right"
            v-if="(form.auditStatus == '3' || form.auditStatus == '2') && commissionType == 0"
            type="primary"
            :beforePrintFn="print"
          />
          <a-button
            v-if="commissionType == 1 && !resolveInfo"
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED',true)"
          >提交</a-button>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { insertSelective, updateByPrimaryKeySelective, getCommercialPerSupplementaryPaymentById, print, insertCommissionFile } from '@/api/businessAffairs/riskRefund'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import moment from 'moment'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import SelectProjectJob from '@/components/Select/SelectProjectJob' // 项目
import { paymentList } from './model.js'
import { getOrgEmployeesListBy } from '@/api/commons'
import { getProcessNodeList, completeTask } from '@/api/process'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal,
    SelectPersonByProject,
    SelectProjectJob,
    SelectProject
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { projectDeptId: void 0, commissionFileInfoList: [], projectId: '' }, // 表单
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        proposerId: [{ required: true, message: '请选择' }],
        proposerPostId: [{ required: true, message: '请选择' }],
        idCard: [{ required: true, message: '请输入' }],
        paymentAmount: [{ required: true, message: '请输入' }],
        paymentReason: [{ required: true, message: '请选择' }],
        bankAccount: [{ required: true, message: '请输入' }],
        bankName: [{ required: true, message: '请输入' }],
        paymentConditions: [{ required: true, message: '请输入' }],
        fileInfoList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }],
        commissionFileInfoList: [{ type: 'array', required: true, message: '请上传补缴收据', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件

      disabledDateList: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoList')
        })
      }
    },
    // 监听附件实现附件校验
    'form.commissionFileInfoList'() {
      if (this.commissionType == 1 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('commissionFileInfoList')
        })
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
 async mounted() {
    if (this.commissionType == 1) {
      this.$route.meta.title = '个人风险金补缴 补缴收据上传'
    } else {
      this.$route.meta.title = ['个人风险金补缴 查看', '个人风险金补缴 编辑', '个人风险金补缴 新增'][this.editModel]
    }

    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getCommercialPerSupplementaryPaymentById({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = { ...this.form, ...res.data }
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.projectId = this.$currentPost().id
      console.log(this.form.projectId, 'this.form.projectId')
      this.$nextTick(() => {
        this.init = true
      })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('commercial_per_supplementary_payment_audit');
  },
  computed: {
    // 是否是业务待办查看处理信息
    resolveInfo: {
      get() {
        return this.$route.query?.resolveInfo === 'true'
      },
      set() {}
    },
    formList() {
      return [
        {
          label: "所属单位",
          keyName: "projectId",
          disabled: true,
          type: 'orgTree',
          span: 16,
          isNeedAuth: true,
          checkStrictly: true,
          isAutoSelectFirst: true,
          rules: [{ required: true, message: "请选择", trigger: "change" }]
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     this.form.projectDeptId = e?.projectDeptId
        //   }
        // },
        {
          keyName: 'proposerId',
          type: SelectPersonByProject,
          disabled: this.editModel == 0,
          label: '补缴申请人',
          attrs: {
            // [currentLabel.sync]: form.returnApplier,
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId,
            mode: 'combobox',
            optionLabelProp: 'children'
          },
          personChanged: (e) => {
            this.form.proposerName = e?.employeeName
          }
        },

        {
          keyName: 'proposerPostId',
          type: SelectProjectJob,
          disabled: this.editModel == 0,
          label: '申请人岗位',
          attrs: {
            projectDeptId: this.form.projectDeptId,
            isClear: this.editModel == 2
          },
          getOption: (e) => {
            this.form.proposerPostName = e?.name
          }
        },
        {
          keyName: 'idCard',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '身份证号码'
        },
        {
          keyName: 'paymentAmount',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '补缴金额(元)'
        },
        {
          keyName: 'paymentReason',
          type: 'a-select',
          label: '补缴原因',
          disabled: this.editModel == 0,
          data: paymentList
        },
        {
          keyName: 'bankAccount',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '银行账号'
        },
        {
          keyName: 'bankName',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '开户行名称'
        },
        {
          keyName: 'paymentConditions',
          type: 'BaseTextarea',
          label: '补缴情况说明',
          disabled: this.editModel == 0,

          span: 24
        },
        {
          slot: true,
          keyName: 'fileInfoList',
          label: '附件上传',
          span: 24
        }
      ]
    },
    auditSWJL() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'PDLXMJL',
          span: 24
        },
        {
          keyName: 'opinionsXMJL',
          type: 'BaseTextarea',
          label: '审批意见',
          disabled: true,
          span: 24
        },
        {
          keyName: 'taskName',
          type: 'BaseInput',
          label: '当前节点名称',
          disabled: true,
          hidden: this.taskDefKey != 'PDLSWJL' && this.taskDefKey != 'PDLXMJL',
          span: 8
        },
        {
          keyName: 'currentUser',
          type: 'BaseInput',
          label: '审批人',
          disabled: true,
          hidden: this.taskDefKey != 'PDLSWJL' && this.taskDefKey != 'PDLXMJL',
          span: 8
        },
        {
          keyName: 'currentTime',
          type: 'BaseInput',
          label: '审批时间',
          disabled: true,
          hidden: this.taskDefKey != 'PDLSWJL' && this.taskDefKey != 'PDLXMJL',
          span: 8
        },
        {
          keyName: 'durationInMillis',
          type: 'BaseInput',
          label: '当前滞留时间',
          disabled: true,
          hidden: this.taskDefKey != 'PDLSWJL' && this.taskDefKey != 'PDLXMJL',
          span: 8
        }
      ]
    },
    auditBCSWFWBJL() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'BCSWFWBJL',
          span: 24
        },
        {
          keyName: 'opinionsBCSWFWBJL',
          type: 'BaseTextarea',
          label: '审批意见',
          disabled: true,
          span: 24
        }
      ]
    },
    auditBCLZJJS() {
      return [
        {
          slot: true,
          customItemSlot: true,
          keyName: 'BCLZJJS',
          span: 24
        },
        {
          keyName: 'opinionsBCLZJJS',
          type: 'BaseTextarea',
          label: '审批意见',
          disabled: true,
          span: 24
        }
      ]
    },
    formUpload() {
      return [
        {
          slot: true,
          keyName: 'commissionFileInfoList',
          label: '补缴收据',
          span: 24
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
    },
    getProjectInfo(val) {
      this.form.projectDeptId = val.projectDeptOrgId
    },
    // 打印
    print() {
      return print({ id: this.id }).then((res) => {
        return res.data.content
      })
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        } else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      console.log(flag)
      return flag
    },
    /**
     * 提交表单
     */
    handleSubmit(status,flag) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true

      let form = this.$clone(this.form)
      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      let api = this.commissionType == 0 ? [updateByPrimaryKeySelective, insertSelective][this.editModel - 1] : insertCommissionFile // 根据操作切换url地址
      this.submitApprovalConfirm(status =='SUBMITTED' && !flag ?this.processConfig: 6 ,(newFlag)=>{
        if(!newFlag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          //flag 为true 是待办，不需要选择审批
          if(status =='SUBMITTED' && !flag) {
            //提交时，返回id
                this.businessId = res.data?.id || this.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
                this.$multiTab.close()
          }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
.item {
  margin-left: 60px;
  margin-bottom: 0;
}
.item .ant-form-item {
  margin-top: -28px;
}
</style>
